#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings


def GetNumberOfStationAssembliesListedOnForm(station=None, Viewer=False):
    if(station):
        NumberOfStationAssembliesListedOnForm=Assembly.objects.filter(Station=station).count() + 10
    else:
        if(Viewer):
            NumberOfStationAssembliesListedOnForm=1
        else:
            NumberOfStationAssembliesListedOnForm=10
    return NumberOfStationAssembliesListedOnForm

def GetNumberOfSpanAssembliesListedOnForm(span=None, Viewer=False):
    if(span):
        NumberOfSpanAssembliesListedOnForm=Assembly.objects.filter(Span=span).count() + 10
    else:
        if(Viewer):
            NumberOfSpanAssembliesListedOnForm=1
        else:
            NumberOfSpanAssembliesListedOnForm=10
    return NumberOfSpanAssembliesListedOnForm

def BuildAssemblyForm(DefaultMap, station=None, span=None, Assemblies=None, Viewer=False):
    NumberOfStationAssembliesListedOnForm=GetNumberOfStationAssembliesListedOnForm(station=station, Viewer=Viewer)
    NumberOfSpanAssembliesListedOnForm=GetNumberOfSpanAssembliesListedOnForm(span=span, Viewer=Viewer)
    NumberOfStationAssembliesListedOnForm=max(NumberOfStationAssembliesListedOnForm, NumberOfSpanAssembliesListedOnForm) #Make sure # of Station Assemblies at least matches # of span assemblies
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    #Create Station Compatible Unit Choices
    StationCompatibleUnitChoices=[]
    StationCompatibleUnits=CompatibleUnit.objects.filter(StationIndicator=True).order_by('Name')
    StationCompatibleUnitChoices.append(['-1', 'None'])
    for i in StationCompatibleUnits:
        StationCompatibleUnitChoices.append([i.id, str(i)])
    #Create the MeterFormChoices
    MeterFormChoices=[]
    MeterForms=MeterForm.objects.all().order_by('Name')
    MeterFormChoices.append(['-1', 'None'])
    for i in MeterForms:
        MeterFormChoices.append([i.id, str(i)])
    #Create the MeterServiceTypeChoices
    MeterServiceTypeChoices=[]
    MeterServiceTypes=MeterServiceType.objects.all().order_by('Name')
    MeterServiceTypeChoices.append(['-1', 'None'])
    for i in MeterServiceTypes:
        MeterServiceTypeChoices.append([i.id, str(i)[:12]])
    #Create Span Compatible Unit Choices
    SpanCompatibleUnitChoices=[]
    SpanCompatibleUnits=CompatibleUnit.objects.filter(SpanIndicator=True).order_by('Name')
    SpanCompatibleUnitChoices.append(['-1', 'None'])
    for i in SpanCompatibleUnits:
        SpanCompatibleUnitChoices.append([i.id, str(i)])
    #Create StationAssemblyManufacturer Choices
    StationAssemblyManufacturerChoices=[]
    StationAssemblyManufacturerCompanies=Company.objects.all().filter(ManufacturerIndicator=True).order_by('Name')
    StationAssemblyManufacturerChoices.append(['-1', 'None'])
    for i in StationAssemblyManufacturerCompanies:
        StationAssemblyManufacturerChoices.append([i.id, str(i)[:4]])
    #Create StationAssemblyOwner Choices
    StationAssemblyOwnerChoices=[]
    StationAssemblyOwners=AssemblyOwner.objects.all().order_by('Name')
    StationAssemblyOwnerChoices.append(['-1', 'None'])
    for i in StationAssemblyOwners:
        StationAssemblyOwnerChoices.append([i.id, str(i)[:4]])
    #Create InstallStatus Choices
    InstallStatusChoices=[]
    InstallStatusInstall=InstallStatus.objects.filter(Name='Install')[0]
    InstallStatusChoices.append([InstallStatusInstall.id, str(InstallStatusInstall)])
    InstallStatuses=InstallStatus.objects.all().exclude(Name='Install').order_by('Name')
    for i in InstallStatuses:
        InstallStatusChoices.append([i.id, str(i)])
    #Create StakerRecipe Choices
    StakerRecipeChoices=[]
    StakerRecipeChoicesList=range(0, 10)
    for i in StakerRecipeChoicesList:
        StakerRecipeChoices.append([i, str(i)])
    #Create BypassAssembly Choices
    BypassAssemblyChoices=[]
    BypassAssemblies=Assembly.objects.filter(BypassIndicator=True).order_by('CompatibleUnit__Name')
    BypassAssemblyChoices.append(['-1', 'None'])
    for i in BypassAssemblies:
        BypassAssemblyChoices.append([i.id, i.CompatibleUnit.Name])


    #Create TransformerBankType Choices [for setting up/deleting transformer banks at a station]
    TransformerBankTypeChoices=[]
    TransformerBankTypes=TransformerBankType.objects.all().order_by('Name')
    TransformerBankTypeChoices.append(['-1', 'None'])
    for i in TransformerBankTypes:
        TransformerBankTypeChoices.append([i.id, i.Name])
    TransformerBankTypeChoices.append(['-2', 'Delete'])  #Delete all of the transformer banks associated with this station
    
    #Create TransformerBank Choices [for associating/deassociating an individual transformer with a nearby transformer bank]
    TransformerBankChoices=[]
    TransformerBankChoices.append(['-1', 'None'])
    if(station):
        NearbyTransformerBanks=TransformerBank.objects.filter(Station__Point__distance_lte=(station.Point, 200)).order_by('id') #Allow a transformer to be associated with a nearby transformer bank.
    else:
        NearbyTransformerBanks=[]
    for i in NearbyTransformerBanks:
        TransformerBankChoices.append([i.id, str(i.id) + ':  ' + i.TransformerBankType.Name])




    for i in range(0, NumberOfStationAssembliesListedOnForm):
        Dict['StationAssemblyCompatibleUnit' + str(i)]=forms.ChoiceField(StationCompatibleUnitChoices, required=False)
        Dict['StationAssemblyBypassAssembly' + str(i)]=forms.ChoiceField(BypassAssemblyChoices, required=False)
        Dict['StationAssemblyCircuitNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        Dict['StationAssemblyPhaseAIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPhaseBIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPhaseCIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPhaseNeutralIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPrimaryIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblySecondaryIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyServiceIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyBypassIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyID' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['StationAssemblyDeleteIndicator' + str(i)]=forms.BooleanField()
        Dict['StationAssemblyUpdateIndicator' + str(i)]=forms.BooleanField()
        Dict['StationAssemblyUpdateCircuitIndicator' + str(i)]=forms.BooleanField()
        Dict['StationAssemblyOpenIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyRotation' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        if(Assemblies and len(Assemblies) > i):  
            if(Assemblies[i].GetProtectingAssemblyIndicator()):
                AddChoices=[]
                AddChoices.append(['-1', 'None'])
                RemoveChoices=[]
                RemoveChoices.append(['-1', 'None'])
                span=Span()
                Spans=span.GetAllMatching(Assemblies[i].Station)
                for span in Spans:
                    if(not ProtectingAssembly.objects.filter(Span=span).filter(Assembly=Assemblies[i])):
                        AddChoices.append([str(span.id), str(span.id)])
                    else:
                        RemoveChoices.append([str(span.id), str(span.id)])
                Dict['StationAssemblyProtectingAdd' + str(i)]=forms.ChoiceField(AddChoices, required=False)
                Dict['StationAssemblyProtectingRemove' + str(i)]=forms.ChoiceField(RemoveChoices, required=False)
            else:
                Dict['StationAssemblyProtectingAdd' + str(i)] = None
                Dict['StationAssemblyProtectingRemove' + str(i)] = None
        else:
            Dict['StationAssemblyProtectingAdd' + str(i)] = None
            Dict['StationAssemblyProtectingRemove' + str(i)] = None
        Dict['StationAssemblyMeterNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        Dict['StationAssemblySerialNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'1.5'}))
        Dict['StationAssemblyMeterOnPoleIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyMeterDCSINumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        Dict['StationAssemblyMeterForm' + str(i)]=forms.ChoiceField(choices=MeterFormChoices, required=False)
        Dict['StationAssemblyMapNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        Dict['StationAssemblyOldMapNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        Dict['StationAssemblyOwner' + str(i)]=forms.ChoiceField(choices=StationAssemblyOwnerChoices, required=False)
        Dict['StationAssemblyManufacturer' + str(i)]=forms.ChoiceField(choices=StationAssemblyManufacturerChoices, required=False)    
        Dict['StationAssemblyTagNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4'}))
        Dict['StationAssemblyPutIntoServiceDateYear' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2'}))    
        Dict['StationAssemblyPrimaryIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblySecondaryIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyServiceIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPoleStubIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPoleLightIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPoleMeterIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyMeterServiceType' + str(i)]=forms.ChoiceField(choices=MeterServiceTypeChoices, required=False)
        Dict['StationAssemblyIdleIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyPhysicalAddress' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
        Dict['StationAssemblyInstallStatus' + str(i)]=forms.ChoiceField(choices=InstallStatusChoices, required=False)
        Dict['StationAssemblyNumberOfCopies' + str(i)]=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'3'}))
        Dict['StationAssemblyTransformerCutOutIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyStakerWorkOrderid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['StationAssemblyStakerWorkOrderChangeToCurrentIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyStakerWorkOrderDisassociateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['StationAssemblyStakerRecipeNumber' + str(i)]=forms.ChoiceField(choices=StakerRecipeChoices, required=False)
        Dict['StationAssemblyTransformerBank' + str(i)]=forms.ChoiceField(choices=TransformerBankChoices, required=False)

    for i in range(0, NumberOfSpanAssembliesListedOnForm):
        Dict['SpanAssemblyCompatibleUnit' + str(i)]=forms.ChoiceField(SpanCompatibleUnitChoices, required=False)
        Dict['SpanAssemblyCircuitNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5'}))
        Dict['SpanAssemblyPhaseAIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyPhaseBIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyPhaseCIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyPhaseNeutralIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyPrimaryIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblySecondaryIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyServiceIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyID' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['SpanAssemblyDeleteIndicator' + str(i)]=forms.BooleanField()
        Dict['SpanAssemblyUpdateIndicator' + str(i)]=forms.BooleanField()
        Dict['SpanAssemblyIdleIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyInstallStatus' + str(i)]=forms.ChoiceField(choices=InstallStatusChoices, required=False)
        Dict['SpanAssemblyNumberOfCopies' + str(i)]=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'3'}))
        Dict['SpanAssemblyStakerWorkOrderid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['SpanAssemblyStakerWorkOrderChangeToCurrentIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyStakerWorkOrderDisassociateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SpanAssemblyStakerRecipeNumber' + str(i)]=forms.ChoiceField(choices=StakerRecipeChoices, required=False)
    #General Fields for All Stations/Spans
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['MapNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['OldMapNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RoadName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['PreviousStationid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['PreviousSpanid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['PreviousSelectionIndicator']=forms.BooleanField(required=False)
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['SelectMeterNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectDCSINumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectGPSIndicator']=forms.BooleanField()
    Dict['CreateStationIndicator']=forms.BooleanField()
    Dict['MoveStationGPSIndicator']=forms.BooleanField()
    Dict['MoveStationNorth']=forms.FloatField(required=False, widget=forms.TextInput(attrs={'size':'2'}))
    Dict['MoveStationEast']=forms.FloatField(required=False, widget=forms.TextInput(attrs={'size':'2'}))
    Dict['StationComment']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['UpdateStationCommentIndicator']=forms.BooleanField(required=False)
    Dict['DeleteStationIndicator']=forms.BooleanField(required=True)
    Dict['SelectSpanid']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['SpanFarStation']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['CreateSpanIndicator']=forms.BooleanField(required=False)
    Dict['SpanComment']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['SpanTapIndicator']=forms.BooleanField(required=False)
    Dict['StakerStopTraceIndicator']=forms.BooleanField(required=False)
    Dict['UpdateSpanCommentIndicator']=forms.BooleanField(required=False)
    Dict['SpanJointTrenchIndicator']=forms.BooleanField(required=False)
    Dict['DeleteSpanIndicator']=forms.BooleanField(required=False)
    Dict['RunDeleteURDMarkerStationIndicator']=forms.BooleanField(required=False)
    Dict['StationTransformerBank']=forms.ChoiceField(choices=TransformerBankTypeChoices, required=False)
    Dict['StakerWorkOrderid']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['StakerWorkOrderStatus']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['TraceCircuitNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceIndicator'] = forms.BooleanField(required=False)
    Dict['GeoTraceStartStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceSpanidsToStopAt']=forms.CharField(max_length = 250, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceConfirmChangeCircuit']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceConfirmChangeCompatibleUnit']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceConfirmChangePhase']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceFromCircuitNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceToCircuitNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['StakerRecipeReportIndicator']=forms.BooleanField(required=False)
    CompatibleUnitChoices=[]
    CompatibleUnits=CompatibleUnit.objects.all().order_by('Name')
    CompatibleUnitChoices.append(['-1', 'None'])
    for i in CompatibleUnits:
        CompatibleUnitChoices.append([i.id, str(i)])
    Dict['GeoTraceCompatibleUnitFrom']=forms.ChoiceField(CompatibleUnitChoices, required=False)  
    Dict['GeoTraceCompatibleUnitTo']=forms.ChoiceField(CompatibleUnitChoices, required=False)
    PhaseNoneChoices=[['-1', 'None'], ['1', 'A'], ['2', 'B'], ['3', 'C'], ['4', 'N']]
    PhaseAChoices=[['1', 'A'], ['-1', 'None'], ['2', 'B'], ['3', 'C'], ['4', 'N']]
    PhaseBChoices=[['2', 'B'], ['-1', 'None'], ['1', 'A'], ['3', 'C'], ['4', 'N']]
    PhaseCChoices=[['3', 'C'], ['-1', 'None'], ['1', 'A'], ['2', 'B'], ['4', 'N']]
    PhaseNChoices=[['4', 'N'], ['-1', 'None'], ['1', 'A'], ['2', 'B'], ['3', 'C']]
    Dict['GeoTracePhaseNoneTo']=forms.ChoiceField(PhaseNoneChoices, required=False)
    Dict['GeoTracePhaseATo']=forms.ChoiceField(PhaseAChoices, required=False)
    Dict['GeoTracePhaseBTo']=forms.ChoiceField(PhaseBChoices, required=False)
    Dict['GeoTracePhaseCTo']=forms.ChoiceField(PhaseCChoices, required=False)
    Dict['GeoTracePhaseNTo']=forms.ChoiceField(PhaseNChoices, required=False)
    Dict['SplitSpanIndicator']=forms.BooleanField(required=False)
    Dict['ShowSummaryIndicator']=forms.BooleanField(required=False)
    if(Viewer):
        Dict['ShowGridInfoIndicator']=forms.BooleanField(required=False)
    return Dict


def ProcessStationAssembly(form, assemblyFormNumber, SelectionStation, UserName, stakerWorkOrder=None, InstallStatusName='Existing', 
                           UpdateStakerWorkOrderIndicator=True, InventoryCollectionMode=False):
    try:
        Assemblyid=int(form.data['StationAssemblyID' + str(assemblyFormNumber)])
    except:
        Assemblyid='New'
    try:
        CompatibleUnitid=int(form.data['StationAssemblyCompatibleUnit' + str(assemblyFormNumber)])
        compatibleUnit=CompatibleUnit.objects.filter(id__exact=CompatibleUnitid)[0]
        AssemblyName=compatibleUnit.Name
    except:
        compatibleUnit=None
        AssemblyName=''
    BypassAssemblyChoice=COOPGIS_FormMisc.FormGetObjectFromid(form, 'StationAssemblyBypassAssembly' + str(assemblyFormNumber), Assembly)
    if BypassAssemblyChoice:
       BypassAssemblyChoiceid, BypassAssemblyChoiceIndexWhenReverseSorted=BypassAssemblyChoice.GetCommandidData()
    else:
       BypassAssemblyChoiceid=BypassAssemblyChoiceIndexWhenReverseSorted=-1
        
    try:
        CircuitNumber=int(form.data['StationAssemblyCircuitNumber' + str(assemblyFormNumber)])
    except:
        CircuitNumber=0
    PhaseAIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyPhaseAIndicator' + str(assemblyFormNumber))
    PhaseBIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyPhaseBIndicator' + str(assemblyFormNumber))
    PhaseCIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyPhaseCIndicator' + str(assemblyFormNumber))
    PhaseNeutralIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyPhaseNeutralIndicator' + str(assemblyFormNumber))
    PrimaryIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyPrimaryIndicator' + str(assemblyFormNumber))
    SecondaryIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblySecondaryIndicator' + str(assemblyFormNumber))
    ServiceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyServiceIndicator' + str(assemblyFormNumber))
    BypassIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationAssemblyBypassIndicator' + str(assemblyFormNumber))
    transformerBankActionCode=COOPGIS_FormMisc.FormGetInteger(form, 'StationAssemblyTransformerBankActionCode' + str(assemblyFormNumber))
    try:
        AssemblyUpdateIndicator=bool(form.data['StationAssemblyUpdateIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        if(InventoryCollectionMode and AssemblyName):
            AssemblyUpdateIndicator=True
        else:
            AssemblyUpdateIndicator=False
    try:
        StationAssemblyUpdateCircuitIndicator=bool(form.data['StationAssemblyUpdateCircuitIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        StationAssemblyUpdateCircuitIndicator=False
    try:
        AssemblyDeleteIndicator=bool(form.data['StationAssemblyDeleteIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        AssemblyDeleteIndicator=False
    try:
        OpenIndicator=bool(form.data['StationAssemblyOpenIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        OpenIndicator=False
    try:
        Rotation=float(form.data['StationAssemblyRotation' + str(assemblyFormNumber)])
    except:
        Rotation=0
    try:
        MeterNumber=form.data['StationAssemblyMeterNumber' + str(assemblyFormNumber)] 
    except:
        MeterNumber=''
    try:
        SerialNumber=form.data['StationAssemblySerialNumber' + str(assemblyFormNumber)] 
    except:
        SerialNumber=''
    try:
        MeterOnPoleIndicator=bool(form.data['StationAssemblyMeterOnPoleIndicator' + str(assemblyFormNumber)] == 'on') 
    except:
        MeterOnPoleIndicator=False
    try:
        MeterDCSINumber=form.data['StationAssemblyMeterDCSINumber' + str(assemblyFormNumber)] 
    except:
        MeterDCSINumber=''
    try:
        MapNumber=form.data['StationAssemblyMapNumber' + str(assemblyFormNumber)]
    except:
        MapNumber=''
    try:
        OldMapNumber=form.data['StationAssemblyOldMapNumber' + str(assemblyFormNumber)] 
    except:
        OldMapNumber=''
    try:
        MeterNumber=form.data['StationAssemblyMeterNumber' + str(assemblyFormNumber)] 
    except:
        MeterNumber=''
    try:
        Ownerid=int(form.data['StationAssemblyOwner' + str(assemblyFormNumber)])
        owner=AssemblyOwner.objects.filter(id__exact=Ownerid)[0]
        OwnerName=owner.Name
    except:
        owner=None
        OwnerName=''
    try:
        AssemblyManufacturerid=int(form.data['StationAssemblyManufacturer' + str(assemblyFormNumber)])
        manufacturer=Company.objects.filter(id__exact=AssemblyManufacturerid)[0]
        ManufacturerName=manufacturer.Name
    except:
        manufacturer=None
        ManufacturerName=''
    try:
        TagNumber=form.data['StationAssemblyTagNumber' + str(assemblyFormNumber)] 
    except:
        TagNumber=''
    try:
        Year=int(form.data['StationAssemblyPutIntoServiceDateYear' + str(assemblyFormNumber)])
        PutIntoServiceDate=datetime.datetime(Year, 1, 1)
    except:
        PutIntoServiceDate=datetime.datetime(1925, 1, 1)
    try:
        PoleStubIndicator=form.data['StationAssemblyPoleStubIndicator' + str(assemblyFormNumber)] 
    except:
        PoleStubIndicator=False
    try:
        PoleLightIndicator=bool(form.data['StationAssemblyPoleLightIndicator' + str(assemblyFormNumber)] == 'on') 
    except:
        PoleLightIndicator=False
    try:
        meterFormid=int(form.data['StationAssemblyMeterForm' + str(assemblyFormNumber)])
        meterForm=MeterForm.objects.filter(id=meterFormid)[0]
        MeterFormName=meterForm.Name
    except:
        meterForm=None
        MeterFormName=''  
    try:
        PoleMeterIndicator=form.data['StationAssemblyPoleMeterIndicator' + str(assemblyFormNumber)] 
    except:
        PoleMeterIndicator=False
    try:
        MeterServiceTypeid=int(form.data['StationAssemblyMeterServiceType' + str(assemblyFormNumber)])
        meterServiceType=MeterServiceType.objects.filter(id__exact=MeterServiceTypeid)[0]
        MeterServiceTypeName=meterServiceType.Name
    except:
        meterServiceType=None
        MeterServiceTypeName=''
    try:
        PhysicalAddress=form.data['StationAssemblyPhysicalAddress' + str(assemblyFormNumber)]
    except:
        PhysicalAddress=''
    try:
        IdleIndicator=bool(form.data['StationAssemblyIdleIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        IdleIndicator=False
    installStatus=InstallStatus.objects.filter(Name__exact='Existing')[0]

    try:
        ProtectingSpanAddid=int(form.data['StationAssemblyProtectingAdd' + str(assemblyFormNumber)])
        ProtectingSpanAdd=Span.objects.filter(id=ProtectingSpanAddid)[0]
    except:
        ProtectingSpanAdd=None
    try:
        ProtectingSpanRemoveid=int(form.data['StationAssemblyProtectingRemove' + str(assemblyFormNumber)])
        ProtectingSpanRemove=Span.objects.filter(id=ProtectingSpanRemoveid)[0]
    except:
        ProtectingSpanRemove=None
    try:
        InstallStatusid=int(form.data['StationAssemblyInstallStatus' + str(assemblyFormNumber)])
        installStatus=InstallStatus.objects.filter(id__exact=InstallStatusid)[0]
        InstallStatusName=installStatus.Name
    except:
        pass #InstallStatusName is set to default by this ProcessStationAssembly function.
    try:
        NumberOfCopies=int(form.data['StationAssemblyNumberOfCopies' + str(assemblyFormNumber)])
    except:
        NumberOfCopies=0
    if(NumberOfCopies > 9 and AssemblyName != 'M2-1S'):
        NumberOfCopies=9
    if(stakerWorkOrder):
        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=stakerWorkOrder.GetCommandidData()
    else:
        StakerWorkOrderid=None
        StakerWorkOrderIndexWhenReverseSorted=-1
    try:
        TransformerCutOutIndicator=bool(form.data['StationAssemblyTransformerCutOutIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        TransformerCutOutIndicator=False
    try:
        StakerWorkOrderDisassociateIndicator=bool(form.data['StationAssemblyStakerWorkOrderDisassociateIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        StakerWorkOrderDisassociateIndicator=False
    try:
        StakerWorkOrderUpdateIndicator=bool(form.data['StationAssemblyStakerWorkOrderChangeToCurrentIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        StakerWorkOrderUpdateIndicator=False
    try:
        stakerRecipeNumber=int(form.data['StationAssemblyStakerRecipeNumber' + str(assemblyFormNumber)])
        StakerRecipeNumberException=False
    except:
        stakerRecipeNumber=0
        StakerRecipeNumberException=True

    transformerBank=COOPGIS_FormMisc.FormGetObjectFromid(form, 'StationAssemblyTransformerBank' + str(assemblyFormNumber), TransformerBank)
    if(transformerBank):
        transformerBankid, transformerBankIndexWhenReverseSorted=transformerBank.GetCommandidData()
    else:
        transformerBankid=None
        transformerBankIndexWhenReverseSorted=-1

    if(not SelectionStation):
        pass #Do not attempt any actions if a station is not selected
    elif(AssemblyUpdateIndicator):
        while(NumberOfCopies > 1):
            command=Command()
            command=command.Create(Name='CreateStationAssembly', AssemblyName=AssemblyName, StartPoint=SelectionStation.Point, TagNumber=TagNumber, 
                                   PutIntoServiceDate=PutIntoServiceDate, PrimaryIndicator=PrimaryIndicator, SecondaryIndicator=SecondaryIndicator, 
                                   PoleStubIndicator=PoleStubIndicator, PoleLightIndicator=PoleLightIndicator, PoleGuyIndicator=False, 
                                   PoleMeterIndicator=PoleMeterIndicator, OwnerName=OwnerName, ManufacturerName=ManufacturerName, 
                                   MeterFormName=MeterFormName, OpenIndicator=OpenIndicator, Rotation=Rotation,  
                                   MeterOnPoleIndicator=MeterOnPoleIndicator, PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator,
                                   PhaseCIndicator=PhaseCIndicator, PhaseNeutralIndicator=PhaseNeutralIndicator, CircuitNumber=CircuitNumber,
                                   SerialNumber=SerialNumber, MeterNumber=MeterNumber, MeterDCSINumber=MeterDCSINumber, 
                                   MapNumber=MapNumber, OldMapNumber=OldMapNumber,
                                   ServiceIndicator=ServiceIndicator, MeterServiceTypeName=MeterServiceTypeName, CommandUserName=UserName,
                                   CommandReadyToProcessIndicator=True, PhysicalAddress=PhysicalAddress, IdleIndicator=IdleIndicator, 
                                   InstallStatus=InstallStatusName, StakerWorkOrderid=StakerWorkOrderid, 
                                   StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted, StakerRecipeNumber=stakerRecipeNumber,
                                   TransformerBankid=transformerBankid, TransformerBankIndexWhenReverseSorted=transformerBankIndexWhenReverseSorted)
            assembly=command.Process()
            NumberOfCopies=NumberOfCopies - 1
        if(Assemblyid == 'New' and AssemblyName):  #Create a New Assembly 
            command=Command()
            command=command.Create(Name='CreateStationAssembly', AssemblyName=AssemblyName, StartPoint=SelectionStation.Point, TagNumber=TagNumber, 
                                 PutIntoServiceDate=PutIntoServiceDate, PrimaryIndicator=PrimaryIndicator, SecondaryIndicator=SecondaryIndicator, 
                                 PoleStubIndicator=PoleStubIndicator, PoleLightIndicator=PoleLightIndicator, PoleGuyIndicator=False, 
                                 PoleMeterIndicator=PoleMeterIndicator, OwnerName=OwnerName, ManufacturerName=ManufacturerName, 
                                 MeterFormName=MeterFormName, OpenIndicator=OpenIndicator,  Rotation=Rotation,
                                 MeterOnPoleIndicator=MeterOnPoleIndicator, PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator,
                                 PhaseCIndicator=PhaseCIndicator, PhaseNeutralIndicator=PhaseNeutralIndicator, CircuitNumber=CircuitNumber,
                                 SerialNumber=SerialNumber, MeterNumber=MeterNumber, MeterDCSINumber=MeterDCSINumber, 
                                 MapNumber=MapNumber, OldMapNumber=OldMapNumber, 
                                 ServiceIndicator=ServiceIndicator, MeterServiceTypeName=MeterServiceTypeName, CommandUserName=UserName,
                                 PhysicalAddress=PhysicalAddress, IdleIndicator=IdleIndicator, InstallStatus=InstallStatusName, 
                                 StakerWorkOrderid=StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted,
                                 StakerRecipeNumber=stakerRecipeNumber, TransformerBankid=transformerBankid, 
                                 TransformerBankIndexWhenReverseSorted=transformerBankIndexWhenReverseSorted)
            assembly=command.Process()
        elif(AssemblyName):  #Assembly already exists, edit it 
            AssemblyToEdit=Assembly.objects.filter(id=Assemblyid)[0]
            if(StakerRecipeNumberException):  #Do not overwrite an Assembly Staker Recipe Setting if none was sent from the form for an existing Assembly
                stakerRecipeNumber=AssemblyToEdit.StakerRecipeNumber
            if(AssemblyToEdit.ResidesOnServerIndicator):
                command=Command()
                if(not UpdateStakerWorkOrderIndicator and AssemblyToEdit.StakerWorkOrder):
                    StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                elif(StakerWorkOrderDisassociateIndicator):
                    StakerWorkOrderid=None
                    StakerWorkOrderIndexWhenReverseSorted=-1
                elif(not StakerWorkOrderUpdateIndicator):
                    if(AssemblyToEdit.StakerWorkOrder):
                        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                #raise(Exception(str(PhaseAIndicator)))
                command=command.Create(Name='EditAssembly', Assemblyid=Assemblyid, AssemblyName=AssemblyName,  
                                 TagNumber=TagNumber, PutIntoServiceDate=PutIntoServiceDate, 
                                 PrimaryIndicator=PrimaryIndicator, SecondaryIndicator=SecondaryIndicator, ServiceIndicator=ServiceIndicator, 
                                 BypassIndicator=BypassIndicator, PoleStubIndicator=PoleStubIndicator,             
                                 PoleLightIndicator=PoleLightIndicator, PoleGuyIndicator=False, 
                                 PoleMeterIndicator=PoleMeterIndicator, OwnerName=OwnerName, ManufacturerName=ManufacturerName, 
                                 MeterFormName=MeterFormName, OpenIndicator=OpenIndicator,  Rotation=Rotation,
                                 MeterOnPoleIndicator=MeterOnPoleIndicator, PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator,
                                 PhaseCIndicator=PhaseCIndicator, PhaseNeutralIndicator=PhaseNeutralIndicator,
                                 CircuitNumber=CircuitNumber, SerialNumber=SerialNumber, 
                                 MeterNumber=MeterNumber, MeterDCSINumber=MeterDCSINumber, MapNumber=MapNumber, OldMapNumber=OldMapNumber,
                                 MeterServiceTypeName=MeterServiceTypeName, CommandUserName=UserName,
                                 PhysicalAddress=PhysicalAddress, IdleIndicator=IdleIndicator, InstallStatus=InstallStatusName,
                                 StakerWorkOrderid=StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted,
                                 StakerRecipeNumber=stakerRecipeNumber, TransformerBankid=transformerBankid, 
                                 TransformerBankIndexWhenReverseSorted=transformerBankIndexWhenReverseSorted)
                command.Process()
            else:
                command=Command.objects.filter(id=AssemblyToEdit.CreateCommand.id)[0]
                command.Set('AssemblyName', compatibleUnit.Name)
                command.Set('CircuitNumber', CircuitNumber)
                command.Set('PhaseAIndicator', PhaseAIndicator)
                command.Set('PhaseBIndicator', PhaseBIndicator)
                command.Set('PhaseCIndicator', PhaseCIndicator)
                command.Set('PhaseNeutralIndicator', PhaseNeutralIndicator)
                command.Set('PutIntoServiceDate', PutIntoServiceDate)
                command.Set('PrimaryIndicator', PrimaryIndicator)
                command.Set('SecondaryIndicator', SecondaryIndicator)
                command.Set('ServiceIndicator', ServiceIndicator)
                if(BypassIndicator):
                    command.Set('BypassIndicator', BypassIndicator)
                command.Set('CommandUserName', UserName)
                command.Set('PoleMeterIndicator', PoleMeterIndicator)
                if(owner):
                    command.Set('OwnerName', owner)
                command.Set('ManufacturerName', ManufacturerName)
                command.Set('MeterFormName', MeterFormName)
                command.Set('OpenIndicator', OpenIndicator)
                command.Set('Rotation', Rotation)
                command.Set('MeterOnPoleIndicator', MeterOnPoleIndicator)
                command.Set('SerialNumber', SerialNumber)
                command.Set('MeterNumber', MeterNumber)
                command.Set('MeterDCSINumber', MeterDCSINumber)
                command.Set('MapNumber', MapNumber)
                command.Set('OldMapNumber', OldMapNumber)
                command.Set('ServiceIndicator', ServiceIndicator)
                command.Set('MeterServiceTypeName', MeterServiceTypeName)
                command.Set('InstallStatus', InstallStatusName)
                NoStakerWorkOrder=False
                if(not UpdateStakerWorkOrderIndicator and AssemblyToEdit.StakerWorkOrder):
                    StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                elif(StakerWorkOrderDisassociateIndicator):
                    StakerWorkOrderid=None
                    StakerWorkOrderIndexWhenReverseSorted=-1
                    NoStakerWorkOrder=True
                elif(not StakerWorkOrderUpdateIndicator):
                    if(AssemblyToEdit.StakerWorkOrder):
                        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                command.Set('StakerWorkOrderid', StakerWorkOrderid)
                command.Set('StakerRecipeNumber', stakerRecipeNumber)
                command.save()
                AssemblyToEdit.CompatibleUnit=compatibleUnit
                AssemblyToEdit.CircuitNumber=CircuitNumber
                AssemblyToEdit.PhaseAIndicator=PhaseAIndicator
                AssemblyToEdit.PhaseBIndicator=PhaseBIndicator
                AssemblyToEdit.PhaseCIndicator=PhaseCIndicator
                AssemblyToEdit.PhaseNeutralIndicator=PhaseNeutralIndicator
                AssemblyToEdit.PutIntoServiceDate=PutIntoServiceDate
                AssemblyToEdit.PrimaryIndicator=PrimaryIndicator
                AssemblyToEdit.SecondaryIndicator=SecondaryIndicator
                AssemblyToEdit.ServiceIndicator=ServiceIndicator
                AssemblyToEdit.BypassIndicator=BypassIndicator
                AssemblyToEdit.TagNumber=TagNumber 
                AssemblyToEdit.PoleStubIndicator=PoleStubIndicator
                AssemblyToEdit.PoleLightIndicator=PoleLightIndicator 
                AssemblyToEdit.PoleMeterIndicator=PoleMeterIndicator
                AssemblyToEdit.AssemblyOwner=owner
                AssemblyToEdit.Manufacturer=manufacturer
                AssemblyToEdit.MeterForm=meterForm
                AssemblyToEdit.OpenIndicator=OpenIndicator
                AssemblyToEdit.Rotation=Rotation
                AssemblyToEdit.MeterOnPoleIndicator=MeterOnPoleIndicator
                AssemblyToEdit.SerialNumber=SerialNumber
                AssemblyToEdit.MeterNumber=MeterNumber
                AssemblyToEdit.MeterDCSINumber=MeterDCSINumber
                try:
                    AssemblyToEdit.MapNumber=int(MapNumber)
                except:
                    AssemblyToEdit.MapNumber=None
                AssemblyToEdit.OldMapNumber=OldMapNumber
                AssemblyToEdit.ServiceIndicator=ServiceIndicator
                AssemblyToEdit.MeterServiceType=meterServiceType
                AssemblyToEdit.IdleIndicator=IdleIndicator
                AssemblyToEdit.PhysicalAddress=PhysicalAddress
                AssemblyToEdit.InstallStatus=installStatus
                if(NoStakerWorkOrder):
                    AssemblyToEdit.StakerWorkOrder=None
                else:
                    AssemblyToEdit.StakerWorkOrder=stakerWorkOrder
                AssemblyToEdit.StakerRecipeNumber=stakerRecipeNumber
                AssemblyToEdit.save()
                AssemblyToEdit.Station.RebuildSymbology()
    elif(StationAssemblyUpdateCircuitIndicator):
            if(AssemblyName):  #Assembly already exists, edit it
                AssemblyToEdit=Assembly.objects.filter(id=Assemblyid)[0]
                MatchingAssemblies=Assembly.objects.filter(Station=AssemblyToEdit.Station).filter(CompatibleUnit__Name=AssemblyName).order_by('id')
                IndexWhenSorted=0
                for assembly in MatchingAssemblies:
                    if assembly.id==AssemblyToEdit.id:
                        break
                    IndexWhenSorted+=1
                AssemblyToEditid, AssemblyToEditIndexWhenReverseSorted= AssemblyToEdit.GetCommandidData()
             
                command=Command()
                command=command.Create(Name='EditAssemblyCircuit', CommandUserName=UserName,
                                       Objectid=AssemblyToEditid, ObjectIndexWhenReverseSorted=AssemblyToEditIndexWhenReverseSorted, 
                                       CompatibleUnitid=CompatibleUnitid, CircuitNumber=CircuitNumber,
                                       OpenIndicator=OpenIndicator, TransformerCutOutIndicator=TransformerCutOutIndicator,
                                       PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator,
                                       PhaseCIndicator=PhaseCIndicator, PhaseNeutralIndicator=PhaseNeutralIndicator,
                                       BypassIndicator=BypassIndicator, BypassAssemblyid=BypassAssemblyChoiceid, 
                                       BypassAssemblyIndexWhenReverseSorted=BypassAssemblyChoiceIndexWhenReverseSorted)
                command.Process()
                if(ProtectingSpanAdd):
                    command=Command()
                    command=command.Create(Name='CreateProtectingAssembly', StartPoint=AssemblyToEdit.Station.Point, 
                                           EndPoint=ProtectingSpanAdd.FarStation(AssemblyToEdit.Station).Point,
                                           AssemblyName=AssemblyToEdit.CompatibleUnit.Name, IndexWhenSorted=IndexWhenSorted, 
                                           CommandUserName=UserName)
                    command.Process()
                if(ProtectingSpanRemove):
                    command=Command()
                    command=command.Create(Name='DeleteProtectingAssembly', StartPoint=AssemblyToEdit.Station.Point, 
                                           EndPoint=ProtectingSpanRemove.FarStation(AssemblyToEdit.Station).Point,
                                           AssemblyName=AssemblyToEdit.CompatibleUnit.Name, IndexWhenSorted=IndexWhenSorted, 
                                           CommandUserName=UserName)
                    command.Process()
    elif(AssemblyDeleteIndicator and not Assemblyid == 'New'):  #Delete an Existing Assembly, cannot delete a new one
        DeleteAssembly(Assemblyid, UserName)





def CopyPreviousFormInformation(form, NewForm):
    FieldNames=['Map',
                'MapNumber',
                'OldMapNumber',
                'RoadName',
                'PreviousStationid',
                'PreviousSpanid',
                'PreviousSelectionIndicator',
                'SelectStationTagNumber',
                'SelectStationid',
                'SelectMeterNumber',
                'SelectDCSINumber',
                'SelectGPSIndicator',
                'CreateStationIndicator',
                'MoveStationGPSIndicator',
                'MoveStationNorth',
                'MoveStationEast',
                'StationComment',
                'UpdateStationCommentIndicator',
                'StationTransformerBank',
                'DeleteStationIndicator',
                'SelectSpanid',
                'SpanFarStation',
                'CreateSpanIndicator',
                'SpanComment',
                'SpanTapIndicator',
                'StakerStopTraceIndicator',
                'UpdateSpanCommentIndicator',
                'SpanJointTrenchIndicator',
                'DeleteSpanIndicator',
                'RunDeleteURDMarkerStationIndicator',
                'TraceCircuitNumber',
                'GeoTraceIndicator',
                'GeoTraceStartStationid',
                'GeoTraceSpanidsToStopAt',
                'GeoTraceConfirmChangeCircuit',
                'GeoTraceConfirmChangeCompatibleUnit',
                'GeoTraceConfirmChangePhase',
                'GeoTraceFromCircuitNumber',
                'GeoTraceToCircuitNumber',
                'GeoTraceCompatibleUnitFrom',
                'GeoTraceCompatibleUnitTo',
                'GeoTracePhaseNoneTo',
                'GeoTracePhaseATo',
                'GeoTracePhaseBTo',
                'GeoTracePhaseCTo',
                'GeoTracePhaseNTo',
                'SplitSpanIndicator',
                'ShowSummaryIndicator']
    for name in FieldNames:
        try:
            NewForm.data[name]=form.data[name]
        except KeyError:
            pass
    return NewForm    

def DeleteAssembly(Assemblyid, UserName):
    """Returns the Order of the command deleted if deleting a command was necessary, otherwise returns 0 if successful"""
    AssemblyToDelete=Assembly.objects.filter(id=Assemblyid)[0]
    if(AssemblyToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeleteAssembly', Assemblyid=Assemblyid, CommandUserName=UserName)
        command=command.Process()
        return 0
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        commandid=int(str(AssemblyToDelete.CreateCommand.id)) #int(str()) to force the query to execute before the deletion
        if(AssemblyToDelete.Station):
            StationOrSpan=AssemblyToDelete.Station
        else:
            StationOrSpan=AssemblyToDelete.Span
        AssemblyToDelete.delete()
        command=Command.objects.filter(id__exact=commandid)
        id=command[0].id
        command[0].delete()
        StationOrSpan.RebuildSymbology()
        return id

def ProcessSpanAssembly(form, assemblyFormNumber, SelectionSpan, UserNameOrIPAddress, stakerWorkOrder=None, InstallStatusName='Existing', 
                        UpdateStakerWorkOrderIndicator=True, InventoryCollectionMode=False):
    try:
        Assemblyid=int(form.data['SpanAssemblyID' + str(assemblyFormNumber)])
    except:
        Assemblyid='New'
    try:
        CompatibleUnitid=int(form.data['SpanAssemblyCompatibleUnit' + str(assemblyFormNumber)])
        compatibleUnit=CompatibleUnit.objects.filter(id__exact=CompatibleUnitid)[0]
        AssemblyName=compatibleUnit.Name
    except:
        compatibleUnit=None
        AssemblyName=''
    try:
        CircuitNumber=int(form.data['SpanAssemblyCircuitNumber' + str(assemblyFormNumber)])
    except:
        CircuitNumber=0
    try:
        PhaseAIndicator=bool(form.data['SpanAssemblyPhaseAIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        PhaseAIndicator=False
    try:
        PhaseBIndicator=bool(form.data['SpanAssemblyPhaseBIndicator' + str(assemblyFormNumber)] == 'on')
    except:
       PhaseBIndicator=False
    try:
        PhaseCIndicator=bool(form.data['SpanAssemblyPhaseCIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        PhaseCIndicator=False
    try:
        PhaseNeutralIndicator=bool(form.data['SpanAssemblyPhaseNeutralIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        PhaseNeutralIndicator=False
    try:
        PrimaryIndicator=bool(form.data['SpanAssemblyPrimaryIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        PrimaryIndicator=False
    try:
        SecondaryIndicator=bool(form.data['SpanAssemblySecondaryIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        SecondaryIndicator=False
    try:
        ServiceIndicator=bool(form.data['SpanAssemblyServiceIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        ServiceIndicator=False
    try:
        IdleIndicator=bool(form.data['SpanAssemblyIdleIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        IdleIndicator=False
    try:
        AssemblyUpdateIndicator=bool(form.data['SpanAssemblyUpdateIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        if(InventoryCollectionMode and AssemblyName):
            AssemblyUpdateIndicator=True
        else:
            AssemblyUpdateIndicator=False
    try:
        AssemblyDeleteIndicator=bool(form.data['SpanAssemblyDeleteIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        AssemblyDeleteIndicator=False
    try:
        InstallStatusid=int(form.data['SpanAssemblyInstallStatus' + str(assemblyFormNumber)])
        installStatus=InstallStatus.objects.filter(id__exact=InstallStatusid)[0]
        InstallStatusName=installStatus.Name
    except:
        installStatus=InstallStatus.objects.filter(Name=InstallStatusName)[0] #InstallStatusName is set as an argument to this ProcessSpanAssembly function
    try:
        NumberOfCopies=int(form.data['SpanAssemblyNumberOfCopies' + str(assemblyFormNumber)])
    except:
        NumberOfCopies=0
    if(NumberOfCopies > 9):
        NumberOfCopies=9
    try:
        StakerWorkOrderDisassociateIndicator=bool(form.data['SpanAssemblyStakerWorkOrderDisassociateIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        StakerWorkOrderDisassociateIndicator=False
    try:
        StakerWorkOrderUpdateIndicator=bool(form.data['SpanAssemblyStakerWorkOrderChangeToCurrentIndicator' + str(assemblyFormNumber)] == 'on')
    except:
        StakerWorkOrderUpdateIndicator=False
    if(stakerWorkOrder):
        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=stakerWorkOrder.GetCommandidData()
    else:
        StakerWorkOrderid=None
        StakerWorkOrderIndexWhenReverseSorted=-1
    try:
        stakerRecipeNumber=int(form.data['SpanAssemblyStakerRecipeNumber' + str(assemblyFormNumber)])
        StakerRecipeNumberException=False
    except:
        stakerRecipeNumber=0
        StakerRecipeNumberException=True
    if(not SelectionSpan):
        pass #Do not attempt any actions if a span is not selected
    elif(AssemblyUpdateIndicator):
        while(NumberOfCopies > 1):
                command=Command()
                StartPoint=SelectionSpan.StartStation.Point
                EndPoint=SelectionSpan.EndStation.Point
                Line=SelectionSpan.Line
                command=command.Create(Name='CreateSpanAssembly', AssemblyName=AssemblyName, StartPoint=StartPoint, EndPoint=EndPoint, Line=Line, 
                                     PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator, PhaseCIndicator=PhaseCIndicator,
                                     PhaseNeutralIndicator=PhaseNeutralIndicator, CircuitNumber=CircuitNumber,  
                                     PrimaryIndicator=PrimaryIndicator, SecondaryIndicator=SecondaryIndicator,ServiceIndicator=ServiceIndicator,
                                     CommandUserName=UserNameOrIPAddress, CommandReadyToProcessIndicator=True, InstallStatus=InstallStatusName,
                                     IdleIndicator=IdleIndicator, StakerWorkOrderid=StakerWorkOrderid,
                                     StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted,
                                     StakerRecipeNumber=stakerRecipeNumber)
                NewSpanAssembly=command.Process()
                NumberOfCopies=NumberOfCopies-1
        if(Assemblyid == 'New' and AssemblyName):  #Create a New Assembly 
            command=Command()
            StartPoint=SelectionSpan.StartStation.Point
            EndPoint=SelectionSpan.EndStation.Point
            Line=SelectionSpan.Line
            command=command.Create(Name='CreateSpanAssembly', AssemblyName=AssemblyName, StartPoint=StartPoint, EndPoint=EndPoint, Line=Line, 
                                 PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator, PhaseCIndicator=PhaseCIndicator,
                                 PhaseNeutralIndicator=PhaseNeutralIndicator, CircuitNumber=CircuitNumber,  
                                 PrimaryIndicator=PrimaryIndicator, SecondaryIndicator=SecondaryIndicator,ServiceIndicator=ServiceIndicator,
                                 CommandUserName=UserNameOrIPAddress, InstallStatus=InstallStatusName,
                                 IdleIndicator=IdleIndicator, StakerWorkOrderid=StakerWorkOrderid,
                                 StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted, StakerRecipeNumber=stakerRecipeNumber)
            NewSpanAssembly=command.Process()                
        elif(AssemblyName):  #Assembly already exists, edit it 
            AssemblyToEdit=Assembly.objects.filter(id=Assemblyid)[0]
            if(StakerRecipeNumberException):  #Do not overwrite an Assembly Staker Recipe Setting if none was sent from the form for an existing Assembly
                stakerRecipeNumber=AssemblyToEdit.StakerRecipeNumber
            if(AssemblyToEdit.ResidesOnServerIndicator):
                StartPoint=SelectionSpan.StartStation.Point
                EndPoint=SelectionSpan.EndStation.Point
                Line=SelectionSpan.Line
                if(not UpdateStakerWorkOrderIndicator and AssemblyToEdit.StakerWorkOrder):
                    StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                elif(StakerWorkOrderDisassociateIndicator):
                    StakerWorkOrderid=None
                    StakerWorkOrderIndexWhenReverseSorted=-1
                elif(not StakerWorkOrderUpdateIndicator):
                    if(AssemblyToEdit.StakerWorkOrder):
                        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                command=Command()
                command=command.Create(Name='EditAssembly', Assemblyid=Assemblyid, AssemblyName=AssemblyName, 
                                 PrimaryIndicator=PrimaryIndicator, SecondaryIndicator=SecondaryIndicator, 
                                 PhaseAIndicator=PhaseAIndicator, PhaseBIndicator=PhaseBIndicator,
                                 PhaseCIndicator=PhaseCIndicator, PhaseNeutralIndicator=PhaseNeutralIndicator, CircuitNumber=CircuitNumber,
                                 ServiceIndicator=ServiceIndicator, CommandUserName=UserNameOrIPAddress, 
                                 InstallStatus=InstallStatusName, IdleIndicator=IdleIndicator, StakerWorkOrderid=StakerWorkOrderid,
                                 StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted, 
                                 StakerRecipeNumber=stakerRecipeNumber)
                command.Process()
            else:
                command=Command.objects.filter(id=AssemblyToEdit.CreateCommand.id)[0]
                command.Set('AssemblyName', compatibleUnit.Name)
                command.Set('CircuitNumber', CircuitNumber)
                command.Set('PhaseAIndicator', PhaseAIndicator)
                command.Set('PhaseBIndicator', PhaseBIndicator)
                command.Set('PhaseCIndicator', PhaseCIndicator)
                command.Set('PhaseNeutralIndicator', PhaseNeutralIndicator)
                command.Set('PrimaryIndicator', PrimaryIndicator)
                command.Set('SecondaryIndicator', SecondaryIndicator)
                command.Set('ServiceIndicator', ServiceIndicator)
                command.Set('CommandUserName', UserNameOrIPAddress)
                command.InstallStatus=InstallStatusName
                NoStakerWorkOrder=False
                if(not UpdateStakerWorkOrderIndicator and AssemblyToEdit.StakerWorkOrder):
                    StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                elif(StakerWorkOrderDisassociateIndicator):
                    StakerWorkOrderid=None
                    StakerWorkOrderIndexWhenReverseSorted=-1
                    NoStakerWorkOrder=True
                elif(not StakerWorkOrderUpdateIndicator):
                    if(AssemblyToEdit.StakerWorkOrder):
                        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=AssemblyToEdit.StakerWorkOrder.GetCommandidData()
                command.Set('StakerWorkOrderid', StakerWorkOrderid)
                command.Set('StakerRecipeNumber', stakerRecipeNumber)
                command.save()
                AssemblyToEdit.CompatibleUnit=compatibleUnit
                AssemblyToEdit.CircuitNumber=CircuitNumber
                AssemblyToEdit.PhaseAIndicator=PhaseAIndicator
                AssemblyToEdit.PhaseBIndicator=PhaseBIndicator
                AssemblyToEdit.PhaseCIndicator=PhaseCIndicator
                AssemblyToEdit.PhaseNeutralIndicator=PhaseNeutralIndicator
                AssemblyToEdit.PrimaryIndicator=PrimaryIndicator
                AssemblyToEdit.SecondaryIndicator=SecondaryIndicator
                AssemblyToEdit.ServiceIndicator=ServiceIndicator
                AssemblyToEdit.InstallStatus=installStatus
                AssemblyToEdit.IdleIndicator=IdleIndicator
                if(NoStakerWorkOrder):
                    AssemblyToEdit.StakerWorkOrder=None
                else:
                    AssemblyToEdit.StakerWorkOrder=stakerWorkOrder
                AssemblyToEdit.StakerRecipeNumber=stakerRecipeNumber
                AssemblyToEdit.save()
                AssemblyToEdit.Span.RebuildSymbology()
    elif(AssemblyDeleteIndicator and not Assemblyid == 'New'):  #Delete an Existing Assembly, cannot delete a new one
        DeleteAssembly(Assemblyid, UserNameOrIPAddress)


def PopulateStationAssemblies(form, SelectionStation, NumberOfStationAssembliesListedOnForm, InstallStatusName='Existing'):
    if(SelectionStation):
        Assemblies=Assembly.objects.filter(Station=SelectionStation).order_by('id')
    else:
        Assemblies=None
    for assemblyFormNumber in range(0, NumberOfStationAssembliesListedOnForm + 1):
        try:
            form.data['StationAssemblyID' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].id)
            form.data['StationAssemblyCompatibleUnit' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].CompatibleUnit.id)
            try:
                form.data['StationAssemblyBypassAssembly' + str(assemblyFormnumber)] = str(Assemblies[assemblyFormNumber].BypassAssembly.id)
            except:
                form.data['StationAssemblyBypassAssembly' + str(assemblyFormNumber)] = -1

            try:
                form.data['StationAssemblyTransformerBank' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].TransformerBank.id)
            except:
                form.data['StationAssemblyTransformerBank' + str(assemblyFormNumber)] = -1

            form.data['StationAssemblyCircuitNumber' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].CircuitNumber)
            form.data['StationAssemblyPhaseAIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseAIndicator
            form.data['StationAssemblyPhaseBIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseBIndicator
            form.data['StationAssemblyPhaseCIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseCIndicator
            form.data['StationAssemblyPhaseNeutralIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseNeutralIndicator
            form.data['StationAssemblyPrimaryIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PrimaryIndicator
            form.data['StationAssemblySecondaryIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].SecondaryIndicator
            form.data['StationAssemblyServiceIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].ServiceIndicator
            form.data['StationAssemblyBypassIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].BypassIndicator
            form.data['StationAssemblyOpenIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].OpenIndicator
            form.data['StationAssemblyRotation' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].Rotation
            form.data['StationAssemblyMeterNumber' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].MeterNumber
            form.data['StationAssemblySerialNumber' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].SerialNumber
            form.data['StationAssemblyMeterOnPoleIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].MeterOnPoleIndicator
            form.data['StationAssemblyMeterDCSINumber' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].MeterDCSINumber
            try:
                form.data['StationAssemblyMeterForm' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].MeterForm.id
            except:
                form.data['StationAssemblyMeterForm' + str(assemblyFormNumber)] = -1
            try:
                form.data['StationAssemblyMeterServiceType' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].MeterServiceType.id
            except:
                form.data['StationAssemblyMeterServiceType' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyMapNumber' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].MapNumber
            form.data['StationAssemblyOldMapNumber' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].OldMapNumber
            try:
                form.data['StationAssemblyOwner' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].AssemblyOwner.id
            except:
                form.data['StationAssemblyOwner' + str(assemblyFormNumber)] = -1
            try:
                form.data['StationAssemblyManufacturer' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].Manufacturer.id
            except:
                form.data['StationAssemblyManufacturer' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyTagNumber' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].TagNumber
            form.data['StationAssemblyPutIntoServiceDateYear' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].PutIntoServiceDate)[:4]
            form.data['StationAssemblyPoleStubIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PoleStubIndicator
            form.data['StationAssemblyPoleLightIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PoleLightIndicator
            form.data['StationAssemblyPoleGuyIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PoleGuyIndicator
            form.data['StationAssemblyDeleteIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyUpdateIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyUpdateCircuitIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyIdleIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].IdleIndicator
            form.data['StationAssemblyPhysicalAddress' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhysicalAddress
            form.data['StationAssemblyProtectingAdd' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyProtectingRemove' + str(assemblyFormNumber)] = -1
            try:
                form.data['StationAssemblyInstallStatus' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].InstallStatus.id
            except:
                form.data['StationAssemblyInstallStatus' + str(assemblyFormNumber)] = InstallStatus.objects.filter(Name__exact=InstallStatusName)[0].id
            form.data['StationAssemblyNumberOfCopies' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyTransformerCutOutIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].TransformerCutOutIndicator
            try:
                form.data['StationAssemblyStakerWorkOrderid' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].StakerWorkOrder.id
            except:
                form.data['StationAssemblyStakerWorkOrderid' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyStakerWorkOrderChangetoCurrentIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyStakerWorkOrderDissociateIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyStakerRecipeNumber' + str(assemblyFormNumber)]=Assemblies[assemblyFormNumber].StakerRecipeNumber
        except:
            form.data['StationAssemblyID' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyTransformerBank' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyCompatibleUnit' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyBypassAssembly' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyCircuitNumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyPhaseAIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPhaseBIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPhaseCIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPhaseNeutralIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPrimaryIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblySecondaryIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyServiceIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyBypassIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyOpenIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyRotation' + str(assemblyFormNumber)] = 0
            form.data['StationAssemblyMeterNumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblySerialNumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyMeterOnPoleIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyMeterDCSINumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyMeterForm' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyMapNumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyOldMapNumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyOwner' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyManufacturer' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyTagNumber' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyPutIntoServiceDateYear' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyPoleStubIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPoleLightIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPoleGuyIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyMeterServiceType' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyUpdateIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyUpdateCircuitIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyDeleteIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyIdleIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyPhysicalAddress' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyProtectingAdd' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyProtectingRemove' + str(assemblyFormNumber)] = -1
            form.data['StationAssemblyInstallStatus' + str(assemblyFormNumber)] = InstallStatus.objects.filter(Name__exact=InstallStatusName)[0].id
            form.data['StationAssemblyTransformerCutOutIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyStakerWorkOrderid' + str(assemblyFormNumber)] = ''
            form.data['StationAssemblyStakerWorkOrderChangetoCurrentIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyStakerWorkOrderDissociateIndicator' + str(assemblyFormNumber)] = False
            form.data['StationAssemblyStakerRecipeNumber' + str(assemblyFormNumber)]=0


def PopulateSpanAssemblies(form, SelectionSpan, NumberOfSpanAssembliesListedOnForm, InstallStatusName='Existing'):
    if(SelectionSpan):
        Assemblies=Assembly.objects.filter(Span=SelectionSpan).order_by('id')
    else:
        Assemblies=None
    for assemblyFormNumber in range(0, NumberOfSpanAssembliesListedOnForm + 1):
        try:
            form.data['SpanAssemblyID' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].id)
            form.data['SpanAssemblyCompatibleUnit' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].CompatibleUnit.id)
            form.data['SpanAssemblyCircuitNumber' + str(assemblyFormNumber)] = str(Assemblies[assemblyFormNumber].CircuitNumber)
            form.data['SpanAssemblyPhaseAIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseAIndicator
            form.data['SpanAssemblyPhaseBIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseBIndicator
            form.data['SpanAssemblyPhaseCIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseCIndicator
            form.data['SpanAssemblyPhaseNeutralIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PhaseNeutralIndicator
            form.data['SpanAssemblyPrimaryIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].PrimaryIndicator
            form.data['SpanAssemblySecondaryIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].SecondaryIndicator
            form.data['SpanAssemblyServiceIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].ServiceIndicator
            form.data['SpanAssemblyUpdateIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyDeleteIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyIdleIndicator' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].IdleIndicator
            try:
                form.data['SpanAssemblyInstallStatus' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].InstallStatus.id
            except:
                form.data['SpanAssemblyInstallStatus' + str(assemblyFormNumber)] = InstallStatus.objects.filter(Name__exact=InstallStatusName)[0].id
            form.data['SpanAssemblyNumberOfCopies' + str(assemblyFormNumber)] = ''
            try:
                form.data['SpanAssemblyStakerWorkOrderid' + str(assemblyFormNumber)] = Assemblies[assemblyFormNumber].StakerWorkOrder.id
            except:
                form.data['SpanAssemblyStakerWorkOrderid' + str(assemblyFormNumber)] = ''
            form.data['SpanAssemblyStakerWorkOrderChangetoCurrentIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyStakerWorkOrderDissociateIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyStakerRecipeNumber' + str(assemblyFormNumber)]=Assemblies[assemblyFormNumber].StakerRecipeNumber
        except:
            form.data['SpanAssemblyID' + str(assemblyFormNumber)] = ''
            form.data['SpanAssemblyCompatibleUnit' + str(assemblyFormNumber)] = -1
            form.data['SpanAssemblyCircuitNumber' + str(assemblyFormNumber)] = ''
            form.data['SpanAssemblyPhaseAIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyPhaseBIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyPhaseCIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyPhaseNeutralIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyPrimaryIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblySecondaryIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyServiceIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyUpdateIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyDeleteIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyIdleIndicator' + str(assemblyFormNumber)] = False   
            form.data['SpanAssemblyInstallStatus' + str(assemblyFormNumber)] = InstallStatus.objects.filter(Name__exact=InstallStatusName)[0].id
            form.data['SpanAssemblyNumberOfCopies' + str(assemblyFormNumber)] = ''   
            form.data['SpanAssemblyStakerWorkOrderid' + str(assemblyFormNumber)] = ''
            form.data['SpanAssemblyStakerWorkOrderChangetoCurrentIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyStakerWorkOrderDissociateIndicator' + str(assemblyFormNumber)] = False
            form.data['SpanAssemblyStakerRecipeNumber' + str(assemblyFormNumber)]=0

def GetCurrentOrPreviousSelection(form, SelectionStation, SelectionSpan):    
    try:
        PreviousSelectionIndicator=bool(form.data['PreviousSelectionIndicator'] == 'on')
    except:
        PreviousSelectionIndicator=False
    if(not PreviousSelectionIndicator):
        return SelectionStation, SelectionSpan
    try:
        PreviousStationid=int(form.data['PreviousStationid'])
        PreviousStation=Station.objects.filter(id=PreviousStationid)[0]
    except:
        PreviousStationid=None
        PreviousStation=None
    try:
        PreviousSpanid=int(form.data['PreviousSpanid'])
        PreviousSpan=Span.objects.filter(id=PreviousSpanid)[0]
    except:
        PreviousSpanid=None
        PreviousSpan=None
    if(PreviousStation):
        ReturnStation=PreviousStation
    else:
        ReturnStation=SelectionStation
    if(PreviousSpan):
        ReturnSpan=PreviousSpan
    else:
        ReturnSpan=SelectionSpan
    return ReturnStation, ReturnSpan




def ProcessSplitSpan(form, span, UserName, stakerWorkOrder):
    try:
        SplitSpanIndicator=bool(form.data['SplitSpanIndicator'] == 'on')
    except:
        SplitSpanIndicator=False
    if(SplitSpanIndicator and span):
        span.SplitSpanInHalf(span, UserName, stakerWorkOrder)
    form.data['SplitSpanIndicator']=False #Do not ever save attempting to split a span on a postback to avoid unintentional splitting of spans







 






def BuildAssetViewerForm(DefaultMap):
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    #Create Station Compatible Unit Choices
    StationCompatibleUnitChoices=[]
    StationCompatibleUnits=CompatibleUnit.objects.filter(StationIndicator=True).order_by('Name')
    StationCompatibleUnitChoices.append(['-1', 'None'])
    for i in StationCompatibleUnits:
        StationCompatibleUnitChoices.append([i.id, str(i)])
    #Create Span Compatible Unit Choices
    SpanCompatibleUnitChoices=[]
    SpanCompatibleUnits=CompatibleUnit.objects.filter(SpanIndicator=True).order_by('Name')
    SpanCompatibleUnitChoices.append(['-1', 'None'])
    for i in SpanCompatibleUnits:
        SpanCompatibleUnitChoices.append([i.id, str(i)])

    Dict['StationCompatibleUnitOne'] = forms.ChoiceField(StationCompatibleUnitChoices, required=False)
    Dict['StationCompatibleUnitTwo'] = forms.ChoiceField(StationCompatibleUnitChoices, required=False)
    Dict['SpanCompatibleUnitOne'] = forms.ChoiceField(SpanCompatibleUnitChoices, required=False)
    Dict['SpanCompatibleUnitTwo'] = forms.ChoiceField(SpanCompatibleUnitChoices, required=False)

    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['UpdateStationIndicator']=forms.BooleanField(required=False)
    Dict['UpdateSpanIndicator']=forms.BooleanField(required=False)
    return Dict



def GetNumberOfWiresInSpan(unit, span):
    Multiplier=0
    Assemblies=Assembly.objects.filter(Span=span).filter(CompatibleUnit=unit)
    for i in Assemblies:
        if(i.PhaseAIndicator):
            Multiplier = Multiplier + 1
        if(i.PhaseBIndicator):
            Multiplier = Multiplier + 1
        if(i.PhaseCIndicator):
            Multiplier = Multiplier + 1
        if(i.PhaseNeutralIndicator):
            Multiplier = Multiplier + 1
    return Multiplier




def ProcessAssetViewerForm(form, UserName):
    import models
    UpdateStationIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateStationIndicator')
    StationCompatibleUnitOne=COOPGIS_FormMisc.FormGetObjectFromid(form, 'StationCompatibleUnitOne', CompatibleUnit)
    StationCompatibleUnitTwo=COOPGIS_FormMisc.FormGetObjectFromid(form, 'StationCompatibleUnitTwo', CompatibleUnit)

    UpdateSpanIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateSpanIndicator')
    SpanCompatibleUnitOne=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SpanCompatibleUnitOne', CompatibleUnit)
    SpanCompatibleUnitTwo=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SpanCompatibleUnitTwo', CompatibleUnit)


    if(UpdateStationIndicator):
        Stations=Station.objects.all().order_by('id')
        if(StationCompatibleUnitOne):
            StationCompatibleUnitOneName=StationCompatibleUnitOne.Name
        else:
            StationCompatibleUnitOneName=''
        if(StationCompatibleUnitTwo):
            StationCompatibleUnitTwoName=StationCompatibleUnitTwo.Name
        else:
            StationCompatibleUnitTwoName=''

        for station in Stations:
            station.CompatibleUnitOneName=StationCompatibleUnitOneName
            if(StationCompatibleUnitOneName):
                station.CompatibleUnitOneNumber=Assembly.objects.filter(Station=station).filter(CompatibleUnit=StationCompatibleUnitOne).count()
            else:
                station.CompatibleUnitOneNumber=0
            station.CompatibleUnitTwoName=StationCompatibleUnitTwoName
            if(StationCompatibleUnitTwoName):
                station.CompatibleUnitTwoNumber=Assembly.objects.filter(Station=station).filter(CompatibleUnit=StationCompatibleUnitTwo).count()
            else:
                station.CompatibleUnitTwoNumber=0
            station.save()

    if(UpdateSpanIndicator):
        Spans=Span.objects.all().order_by('id')
        if(SpanCompatibleUnitOne):
            SpanCompatibleUnitOneName=SpanCompatibleUnitOne.Name
        else:
            SpanCompatibleUnitOneName=''
        if(SpanCompatibleUnitTwo):
            SpanCompatibleUnitTwoName=SpanCompatibleUnitTwo.Name
        else:
            SpanCompatibleUnitTwoName=''

        for span in Spans:
            span.CompatibleUnitOneName=SpanCompatibleUnitOneName
            if(SpanCompatibleUnitOneName):
                span.CompatibleUnitOneNumber=GetNumberOfWiresInSpan(SpanCompatibleUnitOne, span)
            else:
                span.CompatibleUnitOneNumber=0
            span.CompatibleUnitTwoName=SpanCompatibleUnitTwoName
            if(SpanCompatibleUnitTwoName):
                span.CompatibleUnitTwoNumber=GetNumberOfWiresInSpan(SpanCompatibleUnitTwo, span)
            else:
                span.CompatibleUnitTwoNumber=0
            span.save()
    return form




def PopulateAssetViewerForm(form):
    form.data['UpdateStationIndicator']=False
    form.data['UpdateSpanIndicator']=False
    return form





